package com.ece.friendly.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ece.friendly.service.AlerteService;


@Controller
public class AlerteController {
	
	@Autowired
	private AlerteService alerteService;
	
	@RequestMapping(value = "alerte/alerte.view", method = RequestMethod.GET)
	public String home(Locale locale, Model model,HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("alertes", alerteService.getAllAlertes());
		return "alerte";
	}
	
	@RequestMapping(value = "alerte/add.json", method = RequestMethod.POST)
	@ResponseBody  
	public HashMap<String, Object> add(HttpServletRequest request, HttpServletResponse response)
	{
		HashMap<String, Object> map=new HashMap<String,Object>();
		
		String login=null;
	    for(Cookie c: request.getCookies()) {
	        if(c.getName().equals("login"))
	        {
	        	login=c.getValue();
	        	break;
	        }
	    }
	    
	    if(login!=null) 
	    {
	    	long currentDate=new Date().getTime();
	    	alerteService.addAlerte((String)request.getParameter("comment"), (String)request.getParameter("sujet"),login,currentDate);
	    	ArrayList<Object> al=alerteService.getAlerte(login, currentDate);
	    	map.put("alerte",al);
	    }
		return map;
	}

	@RequestMapping(value = "alerte/repondre.json", method = RequestMethod.POST)
	@ResponseBody  
	public HashMap<String, Object> repondre(HttpServletRequest request, HttpServletResponse response)
	{
		HashMap<String, Object> map=new HashMap<String,Object>();
		
		String login=null;
	    for(Cookie c: request.getCookies()) {
	        if(c.getName().equals("login"))
	        {
	        	login=c.getValue();
	        	break;
	        }
	    }
	    
	    if(login!=null) 
	    {
	    	long currentDate=new Date().getTime();int alerte=Integer.parseInt(request.getParameter("id"));
	    	alerteService.repondre((String)request.getParameter("comment"), alerte,login,currentDate);
	    	map.put("repondre",alerteService.getRepondre(alerte, currentDate));
	    }
		return map;
	}

}
